import { Input ,DatePicker} from "antd";
import dayjs from "dayjs";
import { Checkbox,Radio,Table} from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import { LoadingOutlined, PicCenterOutlined, PlusOutlined } from '@ant-design/icons';
import { useEffect, useState } from "react";
import { message, Upload } from 'antd';
import { Select, Space,Modal,Button  } from 'antd';
import SelectShop from './SelectShop'
import type { UploadChangeParam } from 'antd/es/upload';
import { getTag } from "../api/auth";
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';



interface Iprops {
  groupInfo: any;
  setGroupInfo: Function;
  setCurrent: any;
}
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

// const beforeUpload = (file: RcFile) => {
//   const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
//   if (!isJpgOrPng) {
//     message.error('You can only upload JPG/PNG file!');
//   }
//   const isLt2M = file.size / 1024 / 1024 < 2;
//   if (!isLt2M) {
//     message.error('Image must smaller than 2MB!');
//   }
//   return isJpgOrPng && isLt2M;
// };

 
function AddGroupBuyInfo(props: Iprops) {
  const groupInfo = props.groupInfo;
  const setGroupInfo = props.setGroupInfo;
  const [loading, setLoading] = useState(false);
  const [tag,setTag] = useState({pic:'',id:'',type:''})
  const [tagList,setTagList] = useState([])
  const [tagParams,setTagParams] = useState({current:1,type:1,size:5,total:1})
  const [tempRow,setTempRow] = useState({pic:'',id:'',type:''})
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  useEffect(()=>{
      getTag(tagParams)
      .then(res=>{
        setTagList(res.data.data)
        setTagParams({...tagParams,total:res.data.pagnation.total})
      })
  },[tagParams.current,tagParams.type])
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setGroupInfo({...groupInfo,homePic:url})
      });
      setLoading(false);
      console.log(info,"info")
      setGroupInfo({...groupInfo,homePic:'http://dida100.com:8888'+info.file.response.file.path})
    }
  };
  const handleChange2: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setGroupInfo({...groupInfo,banner:url})
      });
      setLoading(false);
      console.log(info,"info")
      setGroupInfo({...groupInfo,banner:'http://dida100.com:8888'+info.file.response.file.path})
    }
  };
  function getTags(){
    
  }

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
    setTag({...tempRow})
    setGroupInfo({...groupInfo,tag:tempRow.id})
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const columns:Array<any> =[
    {
      title: 'id',
      dataIndex: 'id',
      
      
    },
    {
      title: '名称',
      dataIndex: 'name',
      
      
    },
    {
      title: '图片',
      dataIndex: 'pic' ,
      render:(text:any)=><img src={text} alt='' width='60'/>,
      
    },
    {
      title: '类型',
      dataIndex: 'type' ,
      render:(text:any)=><span>{text==1?'团购':'促销优化'}</span>,
      
    }
  ]
  const tagChange = (key:any,row:any)=>{
    console.log(row,"row")
    setTempRow({...row[0]})
  }
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys: React.Key[], selectedRows:any[]) => {
      setTempRow({...selectedRows[0]})
      console.log("selected",selectedRowKeys)
      setSelectedRowKeys(selectedRowKeys)
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };
  const [showShop,setShowShop] = useState(false)
  return (
    <div className="GroupBuyInfo">
      {showShop&&<SelectShop setShowShop={setShowShop} groupInfo={groupInfo} setGroupInfo={setGroupInfo}></SelectShop>}
      <dl>
        <dt>活动设置</dt>
        <dd>
          <p>
            <span>活动名称：</span>
            <Input
              value={groupInfo.name}
              onChange={(e) =>
                setGroupInfo({ ...groupInfo, name: e.target.value })
              }
            />
          </p>
          <p>
            <span>活动时间：</span>
            <span>
            <DatePicker
             showTime
             value={groupInfo.startTime===''?undefined:dayjs(groupInfo.startTime)}
            format={"YYYY-MM-DD HH:mm:ss"}
            onChange={(val,str)=>{
              setGroupInfo({...groupInfo,startTime:str})
            }} />
            -至-
             <DatePicker
             showTime
             value={groupInfo.endTime===''?undefined:dayjs(groupInfo.endTime)}
            format={"YYYY-MM-DD HH:mm:ss"}
            onChange={(val,str)=>{
              setGroupInfo({...groupInfo,end:str})
            }} />
            </span>
          </p>
          <p>
            <span>广告语：</span>
            <Input
              value={groupInfo.slogan}
              onChange={(e) =>
                setGroupInfo({ ...groupInfo, slogan: e.target.value })
              }
            />
          </p>
          <p>
            <span>首页展示：</span>
            
            <Checkbox checked={groupInfo.showHome} 
            onChange={e=>{setGroupInfo({...groupInfo,showHome:Number(e.target.checked)})}}></Checkbox>
          </p>
          <p>
            <span>首页展示图：</span>
            <span  style={{width:'auto !important'}}>
            <Upload
        name="file"
       
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        // beforeUpload={beforeUpload }
        action="http://dida100.com:8888/api/file/upload"
        onChange={handleChange}
      >
        {groupInfo.homePic ? <img style={{width:110,height:110,objectFit:'cover'}} src={groupInfo.homePic} alt="avatar" /> : uploadButton}
      </Upload>
      </span>
          </p>
          <p>
            <span>活动主题海报：</span>
            <span  style={{width:'auto !important'}}>
            <Upload
        name="file"
       
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        // beforeUpload={beforeUpload }
        action="http://dida100.com:8888/api/file/upload"
        onChange={handleChange2}
      >
        {groupInfo.banner? <img style={{width:110,height:110,objectFit:'cover'}} src={groupInfo.banner} alt="avatar" /> : uploadButton}
      </Upload>
      </span>
          </p>
          <p>
            <span>活动展示样式：</span>
            <Radio.Group onChange={e=>{setGroupInfo({...groupInfo,showType:e.target.value})}} value={groupInfo.showType}>
            <Radio value={1}>一行一列</Radio>
            <Radio value={2}>一行两列</Radio>
            <Radio value={3}>一行三列</Radio>
           
          </Radio.Group>
          </p>
          
          <p>
            <span>标签： </span>
            <span>
              <Select
               defaultValue={1}
              style={{ width: 120 }}
              onChange={e=>{
                console.log(e,"eeee")
                setTagParams({...tagParams,type:e})
              }}
              options={[
                { value: 1, label: '团购' },
                { value: 2, label: '活动' },
               
              ]}
            />
            <span onClick={()=>setIsModalOpen(true)}>
            {tag.pic?<img src={tag.pic} alt='tag' width="100"/>:<span>选择图片</span>}
            </span>
            
            </span>
            
          </p>
        </dd>
        <dt>规则设置</dt>
        <dd>
          <p>
              <span>预告时间：</span>
              <span>
              <DatePicker
              showTime
              value={groupInfo.previewTime===''?undefined:dayjs(groupInfo.previewTime)}
              format={"YYYY-MM-DD HH:mm:ss"}
              onChange={(val,str)=>{
                setGroupInfo({...groupInfo,previewTime:str})
              }} />
              </span>
          </p>
          <p>
            <span>活动对象：</span>
            <Radio.Group onChange={e=>{setGroupInfo({...groupInfo,target:e.target.value})}} 
            value={groupInfo.target}>
            <Radio value={1}>不限</Radio>
            <Radio value={2}>所有用户</Radio>             
          </Radio.Group>
          </p>
          <p>
            <span>购买限量：</span>
            <Input  onChange={e=>{setGroupInfo({...groupInfo,limitBuy:e.target.value})}} value={groupInfo.limitBuy}/>          
           
          </p>
          <p>
            <span>选择店铺：</span>
            <span>
            <Radio.Group value={groupInfo.shop} onChange={e=>{setGroupInfo({...groupInfo,shop:e.target.value})}}  >
              <Radio value={0}>不限</Radio>
              <Radio value={1}>指定店铺</Radio>             
            </Radio.Group>
              <span onClick={()=>setShowShop(true)}>选择店铺</span>
              <span>{groupInfo.products}</span>
            </span>
          </p>
          <p>
            <span>配送方式：</span>
            <Radio.Group 
            onChange={e=>{setGroupInfo({...groupInfo,deliverWay:e.target.value})}} 
            value={groupInfo.deliverWay}>
            <Radio value={1}>自提</Radio>
            <Radio value={2}>配送</Radio>             
          </Radio.Group>
          </p>
          <p>
              <span>提货时间：</span>
              <span>
              <DatePicker
              showTime
              value={groupInfo.pickTime===''?undefined:dayjs(groupInfo.pickTimeTime)}
              format={"YYYY-MM-DD HH:mm:ss"}
              onChange={(val,str)=>{
                setGroupInfo({...groupInfo,pickTime:str})
              }} />
              </span>
          </p>
        </dd>
      </dl>
      <p style={{textAlign:'right'}}><Button type="primary" onClick={()=>props.setCurrent(1)}>下一步添加活动商品</Button></p>
      <Modal title="选择标签" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
     
      <Table
        rowKey="id"
        rowSelection={{
          type: 'radio',
          ...rowSelection,
        }}
        onChange={pagination=>{
          console.log(pagination,"pagination")
          setTagParams({...tagParams,current:Number(pagination.current)})
        }}
        pagination={{
          pageSize:tagParams.size,
          total:tagParams.total,
          current:tagParams.current
        }}
        columns={columns}
        dataSource={tagList}
      />
      </Modal>
      {JSON.stringify(props.groupInfo)}
    </div>
  );
}

export default AddGroupBuyInfo;
